package org.wanho.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Author：汤小洋
 * Date：2023-04-20 15:47
 * Description：<描述>
 */
@WebServlet("/form")
public class FormServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 获取请求中的参数
         */
        // req.setCharacterEncoding("utf8"); // 解决post请求时中文乱码的问题

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        int age = Integer.parseInt(req.getParameter("age"));
        String[] hobbies = req.getParameterValues("hobbies");
        String contextPath = req.getContextPath(); // 上下文路径，即Web应用名称
        String servletPath = req.getServletPath(); // Servlet路径，即Servlet的url访问路径
        StringBuffer requestURL = req.getRequestURL(); // 请求路径
        String method = req.getMethod();
        String remoteAddr = req.getRemoteAddr();

        System.out.println(username);
        System.out.println(password);
        System.out.println(age);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("contextPath："+contextPath);
        System.out.println("servletPath："+servletPath);
        System.out.println("requestURL："+requestURL);
        System.out.println(method);
        System.out.println(remoteAddr);

        /**
         * 响应客户端
         */
        // resp.setContentType("text/html;charset=utf8");
        // PrintWriter out = resp.getWriter();

        // 判断是否登陆成功
        if("admin".equals(username) && "123".equals(password)){
            // out.println("恭喜你，登陆成功！");

            // 使用 转发 跳转到另一个页面
            // RequestDispatcher dispatcher = req.getRequestDispatcher("success.html");
            // dispatcher.forward(req,resp);
            req.getRequestDispatcher("/WEB-INF/success.html").forward(req, resp);
        }else{
            // out.println("登陆失败，用户名或密码不正确！");

            // 使用 重定向 跳转到另一个页面
            resp.sendRedirect(req.getContextPath() + "/fail.html");
        }

        // out.close();
    }
}
